package com.yuji.aacar.net.core;


import com.yuji.aacar.net.config.HttpConfig;
import com.yuji.aacar.net.convertfactory.JsonConverterFactory;
import com.yuji.aacar.net.entity.BaseEntity;
import com.yuji.aacar.net.exception.RetryWhenNetworkException;
import com.yuji.aacar.net.interceptor.RequestInterceptor;

import java.util.HashMap;
import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;


/**
 * <li>Date: 2017/2/15 </li>
 * <li>Description: http请求核心类 </li>
 */
public class HttpManager<Service> {
    protected static final int DEFAULT_TIMEOUT = 6;
    //    private Service httpService;
    private HashMap<String, Service> serviceMap = new HashMap<>();//服务管理集合
    private volatile static HttpManager INSTANCE; //单例对象
    // protected String url;//请求地址
    private BaseEntity entity;//处理方法对象

    /**
     * 构造方法
     */
    protected HttpManager() {
        //手动创建一个OkHttpClient并设置超时时间
        //initUrl();
        //        httpService = createService(url, aClass);
    }

    /**
     * 初始化okhttp客户端
     */
    private OkHttpClient initOkHttpClient(String ServiceName) {

        OkHttpClient.Builder okHttpBuilder = new OkHttpClient.Builder();
        okHttpBuilder.connectTimeout(HttpConfig.getTimeOut(), TimeUnit.SECONDS);

        //        X509TrustManager manager= HttpCoreDES.getX509TrustManager();
        //        okHttpBuilder.sslSocketFactory(new SSLSocketFactoryCompat(manager),manager);
        okHttpBuilder.addInterceptor(new RequestInterceptor(ServiceName));
        return okHttpBuilder.build();
    }

//    public static OkHttpClient genericClient() {
//        OkHttpClient httpClient = new OkHttpClient.Builder()
//                .addInterceptor(new Interceptor() {
//                    @Override
//                    public Response intercept(Chain chain) throws IOException {
//                        Request request = chain.request()
//                                .newBuilder()
//                                .addHeader("Content-Type", "application/json; charset=UTF-8")
//                                .addHeader("Accept-Encoding", "gzip, deflate")
//                                .addHeader("Connection", "keep-alive")
//                                .addHeader("Accept", "*/*")
//                                .addHeader("Cookie", "add cookies here")
//                                .build();
//                        LogUtil.e("header", request.header("Content-Type"));
//                        return chain.proceed(request);
//                    }
//                })
//                .build();
//
//        return httpClient;
//    }

    /**
     * 创建服务
     *
     * @param url    请求地址
     * @param aClass 服务接口类型
     * @return 服务对象
     */
    public Service createService(String url, Class<Service> aClass) {
        Retrofit retrofit = new Retrofit.Builder()
                .client(initOkHttpClient(aClass.getName()))
//                .client(genericClient())
                .addConverterFactory(JsonConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .baseUrl(url)
                .build();
        return retrofit.create(aClass);
    }


    /**
     * 单例获取方法
     *
     * @return
     */
    public static HttpManager getInstance() {
        if (INSTANCE == null) {
            synchronized (HttpManager.class) {
                if (INSTANCE == null) {
                    INSTANCE = new HttpManager();
                }
            }
        }
        return INSTANCE;
    }

    /**
     * 处理http请求
     *
     * @param
     */
    /*public void doHttpDeal(Observable observable, Context context, HttpOnNextListener httpOnNextListener) {
        doHttpDeal(observable, context, httpOnNextListener, null);
    }

    public void doHttpDeal(Observable observable, HttpOnNextListener httpOnNextListener, HttpOnErrorListener httpOnErrorListener) {
        doHttpDeal(observable, null, httpOnNextListener, httpOnErrorListener);
    }
*/

    /**
     * 线程调度变换
     *
     * @param observable 观察者
     */
    public Observable doHttpDeal(Observable observable) {
        observable = observable
                .retryWhen(new RetryWhenNetworkException())
                .subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread());
        if (entity != null) {
            observable = observable.map(entity.getFunc1());
        }
        return observable;
    }

    /**
     * 供外部调用的服务获取方法
     *
     * @param aClass     服务类型
     * @param baseEntity 外部提供的转换处理方法
     * @return 服务对象
     */
    public static Object getHttpService(Class aClass, BaseEntity baseEntity) {
        getInstance().entity = baseEntity;
        if (!isContainHttpService(aClass) && HttpConfig.serviceMap.get(aClass.getName()) != null) {
            getInstance().serviceMap.put(aClass.getName(), getInstance().createService(((HttpConfig.ServiceInfo) HttpConfig.serviceMap.get(aClass.getName())).getUrl(), aClass));
        }
        return getInstance().serviceMap.get(aClass.getName());
    }

    public static Object getHttpService(Class aClass) {
        return getHttpService(aClass, null);
    }

    /**
     * 初始化url
     */
   /* protected void initUrl() {
        this.url = HttpConfig.getAppUrl();
    }*/

    /**
     * @return 获取服务api总集合
     */
    public static HashMap getHttpServiceMap() {
        return getInstance().serviceMap;
    }

    /**
     * @return 服务集合是否包含了service
     */
    public static boolean isContainHttpService(Class serviceClass) {
        return getInstance().serviceMap.containsKey(serviceClass.getName());
    }

/*    *//**
     * @return 获取ok客户端
     *//*
    public OkHttpClient getOkHttpClient() {
        return okHttpClient;
    }*/


}
